import { get } from '@common'
import { saveAs } from 'file-saver'
import { RouterView } from 'vue-router'
import wujieVue from 'wujie-vue3'
// 动态加载路由
let _modules = null
let _allRouters = null
export const loadView = (component) => {
  if (!_modules) {
    _modules = import.meta.glob('@/views/**/*.vue')
    _allRouters = {}
    for (const i in _modules) {
      _allRouters[i.replace('/src/views/', '')] = _modules[i]
    }
  }
  if (component && component !== 'Layout') {
    return _allRouters[`${component}.vue`]
  }
  return RouterView
}

// 路由跳转，包括子路由
export const routerPush = (item) => {
  // 跳转后的子服务
  const microName = item.microName
  // 当前子服务
  const curLink = (window.$router.currentRoute.value.meta.link || '').replace(/https:\/\//i, '')
  const curMicroName = curLink.split('/').shift()
  const path = item.path
  const query = item.query || {}
  if (!microName || microName !== curMicroName) {
    window.$router.push({
      path,
      query
    })
  }
  if (microName) {
    wujieVue.bus.$emit('main-sub-route', {
      appId: microName,
      data: path
    })
  }
}
// 下载文件流
export const download = async (api, params, fileName) => {
  params = params || {}
  try {
    await get(
      api,
      {
        ...params,
        isHandleError: true
      },
      {
        responseType: 'blob'
      }
    )
  } catch (res) {
    const blob = new Blob([res]) //处理文档流
    saveAs(blob, fileName)
  }
}